package com.changgou.gateway.filter;

import com.changgou.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements GlobalFilter, Ordered {
    private static final String LOGIN_URL="http://localhost:6889/api/oauth/toLogin";
    @Autowired
    private StringRedisTemplate redisTemplate;
    public static String filterPath="/api/wcart/**,/api/wseckillorder,/api/seckill,/api/wxpay,/api/wxpay/**,/api/worder/**,/api/user/**,/api/address/**,/api/wcart/**,/api/cart/**,/api/categoryReport/**,/api/orderConfig/**,/api/order/**,/api/orderItem/**,/api/orderLog/**,/api/preferential/**,/api/returnCause/**,/api/returnOrder/**,/api/returnOrderItem/**";
    public static boolean hasAuthorize(String url) {
        String[] split = filterPath.replace("**", "").split(",");
        for (String value : split) {
            if (url.startsWith(value)) {
                return true;
            }
        }
        return false;
    }
    public String getJtiFromCookie(ServerHttpRequest request) {
        HttpCookie httpCookie = request.getCookies().getFirst("uid");
        if (httpCookie != null){
            String jti = httpCookie.getValue();
            return jti;
        }
        return null;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
       String url=request.getURI().getPath();
        if (!hasAuthorize(url)) {
            return chain.filter(exchange);
        }
        HttpHeaders headers = request.getHeaders();
        String jti = headers.getFirst("jti");
        System.out.println(headers.toString());
        if (StringUtils.isEmpty(jti)) {
            jti = this.getJtiFromCookie(request);
            if (StringUtils.isEmpty(jti)){
                return this.toLoginPage(LOGIN_URL+"?FROM="+request.getURI(),exchange);
            }
            else {
                String redistoken = redisTemplate.boundValueOps(jti).get();
                if (StringUtils.isEmpty(redistoken)) {
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
                request.mutate().header("Authorization", "Bearer " + redistoken);
                return chain.filter(exchange);
            }

        }

        String redistoken = redisTemplate.boundValueOps(jti).get();

        if (StringUtils.isEmpty(redistoken)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        request.mutate().header("Authorization", "Bearer " + redistoken);
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
    private Mono<Void> toLoginPage(String loginUrl,ServerWebExchange exchange){
        ServerHttpResponse response=exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location",loginUrl);
        return response.setComplete();
    }
}
